<template>
  <li
    class="dropdown-item"
    :class="{
      'is-disabled': props.disabled,
      'dropdown-divider': props.divided,
      'has-submenu': slots.submenu,
    }"
    @click="handleClick"
    role="menuitem"
    :aria-disabled="props.disabled"
  >
    <span v-if="slots.icon" class="dropdown-item-icon">
      <slot name="icon"></slot>
    </span>

    <span class="dropdown-item-content">
      <slot></slot>
    </span>

    <span v-if="slots.submenu" class="submenu-arrow"></span>

    <slot name="submenu"></slot>
  </li>
</template>

<script setup lang="ts">
import { inject, useSlots } from "vue";
import { DropdownContextKey, type DropdownItemProps } from "./dropdown.types";

defineOptions({
  name: "DropdownItem",
});

const props = withDefaults(defineProps<DropdownItemProps>(), {
  disabled: false,
  divided: false,
});

const emit = defineEmits<{
  (e: "click", event: MouseEvent): void;
}>();

const slots = useSlots();

// 注入父组件的上下文
const context = inject(DropdownContextKey);

const handleClick = (event: MouseEvent) => {
  if (props.disabled) {
    event.stopPropagation();
    event.preventDefault();
    return;
  }

  // 触发 'click' 事件
  emit("click", event);

  // 调用父组件的 handleItemClick
  if (context) {
    context.handleItemClick(props.command);
  }
};
</script>
